package cn.apestar.modules.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class HttpUtil {

    private static final long serialVersionUID = -8483811141908827663L;

    private static final int TIMEOUT_SECONDS = 200000;

    private static final String POST = "POST";

    private static final String GET = "GET";

    private static HttpClient httpClient = null;

    /**
     * 取得HTTPCLIENT 实列
     * @return
     */
    public static HttpClient getHttpClient() {

        HttpClient httpClient = null;
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
            HttpParams httpParams = httpClient.getParams();
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 100);
        }
        return httpClient;
    }

    /**
     * 同步执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionPost(String URL, List<BasicNameValuePair> formparams) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        if (formparams != null) {
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uefEntity);
        }
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        // post.addHeader("Cookie",
        // "JSESSIONID=BFFD7D3FBB3035850A9968482CF56598;
        // _ga=GA1.2.1877413494.1460614311; __qca=P0-536845267-1460614310994;
        // _ceg.s=o5m182; _ceg.u=o5m182; __atuvc=1%7C15;
        // __atuvs=570f34af09c544ea000; nmstat=1460614391172;
        // NSC_wjq-xxx.jdfmboebjs.vt-iuuqt=ffffffff096c8e3345525d5f4f58455e445a4a423661");
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        return endResponseString;
    }

    /**
     * 同步执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionPostString(String URL, String objectString) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        post.addHeader("content-type", "application/json");
        post.addHeader("Accept", "application/json");
        StringEntity s = new StringEntity(objectString, "UTF-8"); // 中文乱码在此解决
        post.setEntity(s);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        System.out.println(entity.getContent());
        String endResponseString = getStringAsStream(entity.getContent());
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException(URL + "连接失败" + endResponseString);
        }
        return endResponseString;
    }

    /**
     * 同步执行GET传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionGET(String URL, List<BasicNameValuePair> formparams) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        String url = URL;
        if (formparams != null && formparams.size() > 0) {
            url = url + "&" + URLEncodedUtils.format(formparams, HTTP.UTF_8);
        }
        HttpGet get = new HttpGet(url);
        get.addHeader("User-Agent",
                      "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"); // 认证token
        // get.addHeader("Host", "m.58.com");
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(get);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
        entity = remoteResponse.getEntity();
        System.out.println(entity.getContent());
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        return endResponseString;
    }

    /**
     * 异步执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static void ExecutionAsycPost(String URL, List<BasicNameValuePair> formparams) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(uefEntity);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
    }

    /**
     * 取得传输参数
     * @return
     */
    public static List<BasicNameValuePair> getBasicNameValuePair(Map map) {

        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();

        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            formparams.add(new BasicNameValuePair(s, ObjectUtils.toString(map.get(s), "")));
        }

        return formparams;
    }

    /**
     * 对流进行转化
     * @param ins
     * @return
     */
    public static String getStringAsStream(InputStream ins) {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        StringBuffer sbf = new StringBuffer();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        /** 回收资源 */
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = sbf.toString();
        return s;
    }

}